<?php

namespace app\controller;

use think\facade\Request;
use app\BaseController;
use app\ResourceModel;
use app\controller\ResourceController;
use think\facade\Db;

class ResourceUserController extends ResourceController
{


    /**
     * 保存新建的资源
     *
     * @param \think\Request $request
     *
     * @return \think\Response
     */
    public function save(Request $request)
    {
        $data = $this->param;

        $lang_time = 1;
        if (!empty($data['long_time'])) {
            $lang_time = $data['long_time'];
            unset($data['long_time']);
        }
        unset($data['table']);
        if (!empty($data['password'])) {
            $data['password'] = md5($data['password']);
        }

        $userInfo = getLoginInfo();
        $maxNum = Db::name('user')->where('id', $userInfo['id'])->field('max_num')->find();

        if (!empty($data['del_flag']) && ($data['del_flag'] == 0 || $data['del_flag'] == 1)) {
            $data = ['id' => $data['id'], 'del_flag' => $data['del_flag']];
        } else {

            if ($userInfo['id'] > 1) {
                $count = Db::name('user')->where('pid', $userInfo['id'])->count();
                if ($count >= $maxNum['max_num']) {
                    return $this->returnJson(1002, '您已经达到最大创建账号数量');
                }
                $data['pay_time'] = time();
                $data['how_long_time'] = 365 * 86400;
            } else {
                $data['pay_time'] = time();
                $data['how_long_time'] = $lang_time * 86400;
            }
            if (empty($data['id'])) {
                if ($userInfo['id'] == 1) {
                    $data['pid'] = empty($data['pid']) ? 0 : $data['pid'];
                }else{
                    $data['pid'] = empty($data['pid']) ? $userInfo['id'] : $data['pid'];
                }
            }
        }


        $ret = $this->model->editData($data, $this->param['table']);
        return $this->returnJson($ret['code'], $ret['msg']);
    }

    public function delete($id)
    {
        $table = $this->param['table'];
        $result = $this->model->table($this->param['table'])->whereIn('id', json_decode($this->post['ids']))->delete();
        return $result ? $this->returnJson(1001, '删除成功' . $id) : $this->returnJson(1002, '删除失败' . $id);
    }

}
